<script setup lang="ts">
import {ref, onMounted} from 'vue';
import {Avatar, Card, Tag, Tooltip, Button, Divider, Empty, List, message} from 'ant-design-vue';
import {LikeOutlined, StarOutlined, EyeOutlined, MessageOutlined, ArrowLeftOutlined} from '@ant-design/icons-vue';
import dayjs from 'dayjs';
import {useLoginUserStore} from '@/stores/useLoginUserStore';

// 模拟博客数据，根据用户提供的格式
// const blogDetail = ref({
//   id: "1",
//   title: "哈哈哈",
//   tags: ["qwq", "qaq"],
//   content: "<p>泥嚎吗</p>",
//   likeNum: 1,
//   collectNum: 0,
//   viewCount: "0",
//   commentCount: "0",
//   userVO: {
//     id: "1",
//     userAccount: "admin",
//     username: "管理员",
//     userAvatar: "https://cloud-picture-1361877603.cos.ap-guangzhou.myqcloud.com/public/1/2025-09-11_ze1A7F3vUcHALYrf.webp",
//     userProfile: "大家嚎",
//     userTags: ["qwq"],
//     teach: ["音乐", "美术"],
//     learn: ["六级", "雅思"],
//     userRole: "admin",
//     status: 1,
//     points: 0,
//     blogCount: 0,
//     blogTotalView: "0",
//     likeCount: 0,
//     collectCount: 0,
//     followCount: 0,
//     fanCount: 0,
//     createTime: "2025-09-14T05:06:39.000+00:00",
//     updateTime: "2025-09-15T07:36:56.000+00:00"
//   },
//   createTime: "2025-09-21T08:52:42.000+00:00"
// });

const route = useRoute();
const router = useRouter();
const blogId = ref(route.params.id);
const blogDetail = ref<BlogVO>({});
const current = ref(1);
const pageSize = ref(10)

const loginUserStore = useLoginUserStore();
const isLiked = ref(blogDetail.value.isLiked);
const isCollected = ref(false);
const commentText = ref('');
const comments = ref([]);

// 返回上一页
const goBack = () => {
  router.back();
};

// 点赞功能
const handleLike = async () => {
  const res = await likeBlog({
    blogId: blogId.value,
    userId: loginUserStore.loginUser.id,
    isLiked: !blogDetail.value.isLiked
  })
  if (res.data.code === 0 && res.data.data) {

    if (blogDetail.value.isLiked) {
      blogDetail.value.likeNum--;
      message.success("取消点赞成功")
    } else {
      blogDetail.value.likeNum++;
      message.success("点赞成功")
    }
    blogDetail.value.isLiked = !blogDetail.value.isLiked;
  } else {
    message.error("点赞失败，" + res.data.message)
  }

};

// 收藏功能
const handleCollect = async () => {
  const res = await collectBlog({
    blogId: blogId.value,
    userId: loginUserStore.loginUser.id,
    isCollected: !blogDetail.value.isCollected
  })
  if (res.data.code === 0 && res.data.data) {
    if (blogDetail.value.isCollected) {
      blogDetail.value.collectNum--;
      message.success("取消收藏成功")
    } else {
      blogDetail.value.collectNum++;
      message.success("收藏成功")
    }
    blogDetail.value.isCollected = !blogDetail.value.isCollected;
  } else {
    message.error("收藏失败，" + res.data.message)
  }
};


// 格式化时间
const formatTime = (timeString) => {
  return dayjs(timeString).format('YYYY-MM-DD HH:mm');
};

import relativeTime from 'dayjs/plugin/relativeTime';
import {collectBlog, commentBlog, getBlogCommentPage, getBlogVoById, likeBlog, viewBlog} from "@/api/blogController.ts";
import {useRoute, useRouter} from "vue-router";
import BlogVO = API.BlogVO;

dayjs.extend(relativeTime);


//发布评论
const handleComment = async () => {
  const res = await commentBlog({
    blogId: blogId.value,
    text: commentText.value,
    userId: loginUserStore.loginUser.id
  })
  if (res.data.code === 0 && res.data.data) {
    commentText.value = ''
    message.success("评论成功")
    await fetchCommentData()
  } else {
    message.error("网络出现波动，评论失败")
  }
}

//获取博客信息（内容、评论等）
const fetchBlogData = async () => {
  //获取博客信息
  const blogRes = await getBlogVoById({
    id: blogId.value
  })
  if (blogRes.data.code === 0 && blogRes.data.data) {
    blogDetail.value = blogRes.data.data;
    console.log('获取博客信息成功，', blogRes.data.data)
  } else {
    message.error("获取博客信息失败，" + blogRes.data.message)
  }

}
//获取博客评论
const fetchCommentData = async () => {
  //获取博客评论
  const commentRes = await getBlogCommentPage({
    blogId: blogId.value,
    current: current.value,
    pageSize: pageSize.value
  })
  if (commentRes.data.code === 0 && commentRes.data.data) {
    comments.value = commentRes.data.data.records
    console.log("获取博客评论成功，", commentRes.data.data)
  } else {
    message.error("获取博客评论失败，" + commentRes.data.message)
  }
}

onMounted(async () => {
  await fetchBlogData()
  await fetchCommentData()
  await viewBlog({
    id: blogId.value,
  })

})
</script>

<template>

  <div id="BlogDetailPage">
    <div class="blog-detail-container">
      <!-- 返回按钮 -->
      <div class="back-button-container">
        <a-button type="text" @click="goBack">
          <template #icon>
            <ArrowLeftOutlined/>
          </template>
          返回
        </a-button>
      </div>

      <!-- 博客头部信息 -->
      <div class="blog-header">
        <div class="author-info">
          <Avatar :src="blogDetail.userVO?.userAvatar" size="large"/>
          <div class="author-details">
            <div class="username">{{ blogDetail.userVO?.username }}</div>
            <div class="publish-info">
              <span>{{ formatTime(blogDetail.createTime) }}</span>
              <span class="view-count">
                <EyeOutlined/> {{ blogDetail.viewCount }} 浏览
              </span>
            </div>
          </div>
        </div>

        <!-- 博客标题 -->
        <h1 class="blog-title">{{ blogDetail.title }}</h1>

        <!-- 博客标签 -->
        <div class="blog-tags">
          <Tag v-for="tag in blogDetail.tags" :key="tag">
            {{ tag }}
          </Tag>
        </div>
      </div>

      <Divider/>

      <!-- 博客内容 -->
      <div class="blog-content" v-html="blogDetail.content"></div>

      <Divider/>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <a-button
            :type="blogDetail.isLiked ? 'primary' : 'default'"

            @click="handleLike"
        >
          <template #icon>
            <LikeOutlined v-if="blogDetail.isLiked"/>
            <LikeOutlined v-else/>
          </template>
          {{ blogDetail.isLiked ? '已点赞' : '点赞' }} ({{ blogDetail.likeNum }})
        </a-button>

        <a-button
            :type="blogDetail.isCollected ? 'primary' : 'default'"
            @click="handleCollect"
        >
          <template #icon>
            <StarOutlined v-if="blogDetail.isCollected"/>
            <StarOutlined v-else/>
          </template>
          {{ blogDetail.isCollected ? '已收藏' : '收藏' }} ({{ blogDetail.collectNum }})
        </a-button>

        <a-button
            type="default"
        >
          <template #icon>
            <MessageOutlined v-if="isLiked"/>
            <MessageOutlined v-else/>
          </template>
          评论 ({{ blogDetail.commentCount }})
        </a-button>
      </div>


      <!-- 评论区 -->
      <div class="comments-section">
        <h2 class="comments-title">评论 ({{ blogDetail.commentCount }})</h2>

        <!-- 评论输入 -->
        <div class="comment-input-section">
          <Avatar
              :src="loginUserStore.loginUser?.userAvatar || ''"
              class="comment-input-avatar"
          />
          <div class="comment-input-container">
            <textarea
                v-model="commentText"
                class="comment-input"
                placeholder="写下你的评论..."
                rows="3"
            ></textarea>
            <div class="comment-input-actions">
              <a-button type="primary" @click="handleComment">
                发布评论
              </a-button>
            </div>
          </div>
        </div>

        <!-- 评论列表 -->
        <div class="comments-list">
          <Empty v-if="comments.length === 0" description="暂无评论"/>
          <a-comment v-for="comment in comments" :key="comment.id">
            <template #author><a>{{ comment.username }}</a></template>
            <template #avatar>
              <a-avatar :src="comment.userAvatar" alt="头像"/>
            </template>
            <template #content>
              <p>
                {{ comment.text }}
              </p>
            </template>
            <template #datetime>
              <a-tooltip :title="dayjs(comment.createTime).format('YYYY-MM-DD HH:mm:ss')">
                <span>{{ dayjs(comment.createTime).fromNow() }}</span>
              </a-tooltip>
            </template>
          </a-comment>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
#BlogDetailPage {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 24px 0;
}

.blog-detail-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 32px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.back-button-container {
  margin-bottom: 24px;
}

.blog-header {
  margin-bottom: 32px;
}

.author-info {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.author-details {
  margin-left: 16px;
}

.username {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.publish-info {
  display: flex;
  align-items: center;
  gap: 24px;
  font-size: 14px;
  color: #666;
}

.view-count {
  display: flex;
  align-items: center;
  gap: 4px;
}

.blog-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  line-height: 1.4;
}

.blog-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.blog-content {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
  margin-bottom: 24px;
}

.action-buttons {
  display: flex;
  gap: 24px;
  margin-bottom: 32px;
}

.author-card {
  margin-bottom: 32px;
}

.author-card-content {
  display: flex;
  gap: 16px;
}

.author-card-details {
  flex: 1;
}

.author-card-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.author-card-profile {
  font-size: 14px;
  color: #666;
  margin-bottom: 16px;
  line-height: 1.6;
}

.author-card-stats {
  display: flex;
  gap: 32px;
  margin-bottom: 16px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-label {
  font-size: 14px;
  color: #999;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.author-card-tags {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.tag-group {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.tag-group-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
  min-width: 40px;
}

.comments-section {
  margin-top: 40px;
}

.comments-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 24px;
}

.comment-input-section {
  display: flex;
  gap: 16px;
  margin-bottom: 32px;
}

.comment-input-avatar {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
}

.comment-input-container {
  flex: 1;
}

.comment-input {
  width: 100%;
  min-height: 80px;
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  resize: vertical;
  font-size: 14px;
  line-height: 1.6;
  transition: all 0.3s;
}

.comment-input:focus {
  border-color: #1890ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.comment-input-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

.comments-list {
  margin-top: 24px;
}

.comment-list {
  .ant-list-item {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;
  }

  .ant-list-item-meta {
    align-items: flex-start;
  }

  .ant-list-item-meta-title {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 4px;
  }

  .ant-list-item-meta-description {
    font-size: 14px;
    color: #666;
    line-height: 1.6;
  }

  .ant-list-item-extra {
    color: #999;
    font-size: 12px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .blog-detail-container {
    padding: 24px;
  }

  .blog-title {
    font-size: 24px;
  }

  .action-buttons {
    gap: 16px;
  }

  .author-card-content {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .author-card-stats {
    justify-content: center;
  }

  .tag-group {
    justify-content: center;
  }
}
</style>
